package co.sanduche.teach.gallery;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import co.sanduche.models.Models.Person;
import co.sanduche.models.Models.Student;

public class StudentsDBOpenHelper extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION = 1;
	private static final String TABLE_CREATE = "CREATE TABLE students ("
			+ BaseColumns._ID
			+ " INTEGER PRIMARY KEY, name TEXT, photo TEXT, idClass INTEGER);";

	public StudentsDBOpenHelper(Context context) {
		super(context, "TeachStudents", null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(TABLE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

	public List<AndroidStudent> loadAllData(long idClass) {
		ArrayList<AndroidStudent> images = new ArrayList<AndroidStudent>();

		SQLiteDatabase db = getReadableDatabase();
		Cursor res = db.rawQuery("SELECT * FROM students WHERE idClass = "
				+ idClass, new String[0]);
		for (boolean hasNext = res.moveToFirst(); hasNext; hasNext = res
				.moveToNext()) {
			final long id = res.getLong(0);
			final String name = res.getString(1);
			final String photo = res.getString(2);
			AndroidStudent s = new AndroidStudent();
			s.setId(id);
			s.setName(name);
			s.setPhoto(photo);

			images.add(s);
		}
		db.close();
		return images;
	}

	public void saveAll(Long idClass, List<Student> students) {
		SQLiteDatabase db = getWritableDatabase();
		db.delete("students", null, null);
		for (Student s : students) {
			ContentValues values = new ContentValues();
			Person p = s.getPerson();
			values.put("_id", s.getId());
			values.put("name", p.getFirstName() + " " + p.getLastName());
			values.put("idClass", idClass);
			db.insert("students", null, values);
		}
		db.close();

	}
}
